from datetime import datetime, timedelta
import uuid
from app import db

class VenueDevice(db.Model):
    """场馆设备模型"""
    __tablename__ = 'venue_devices'
    
    id = db.Column(db.Integer, primary_key=True)
    venue_id = db.Column(db.Integer, db.ForeignKey('venues.id'), nullable=False, index=True)
    device_type = db.Column(db.String(50), nullable=False, comment='设备类型: door_lock(门锁), light(灯光), camera(摄像头), air_condition(空调)')
    device_name = db.Column(db.String(100), nullable=False, comment='设备名称')
    device_code = db.Column(db.String(50), unique=True, nullable=False, comment='设备编号')
    device_model = db.Column(db.String(100), comment='设备型号')
    control_method = db.Column(db.String(50), nullable=False, comment='控制方式: api(接口), qrcode(二维码), manual(手动)')
    api_endpoint = db.Column(db.String(255), comment='API控制接口地址')
    api_key = db.Column(db.String(255), comment='API密钥')
    has_access_control = db.Column(db.Boolean, default=False, comment='是否有门禁系统')
    access_control_type = db.Column(db.String(50), comment='门禁类型: self(自主门禁), third_party(第三方门禁)')
    qr_code_duration = db.Column(db.Integer, default=300, comment='二维码有效期(秒)')
    status = db.Column(db.SmallInteger, default=1, comment='设备状态: 0禁用 1启用')
    is_online = db.Column(db.Boolean, default=True, comment='设备是否在线')
    last_heartbeat = db.Column(db.DateTime, comment='最后心跳时间')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    venue = db.relationship('Venue', backref='devices')
    access_codes = db.relationship('DeviceAccessCode', backref='device', lazy='dynamic')
    operation_logs = db.relationship('DeviceOperationLog', backref='device', lazy='dynamic')
    
    def __repr__(self):
        return f'<VenueDevice {self.id}: {self.device_name}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'id': self.id,
            'venue_id': self.venue_id,
            'device_type': self.device_type,
            'device_name': self.device_name,
            'device_code': self.device_code,
            'device_model': self.device_model,
            'control_method': self.control_method,
            'api_endpoint': self.api_endpoint,
            'has_access_control': self.has_access_control,
            'access_control_type': self.access_control_type,
            'qr_code_duration': self.qr_code_duration,
            'status': self.status,
            'is_online': self.is_online,
            'last_heartbeat': self.last_heartbeat.strftime('%Y-%m-%d %H:%M:%S') if self.last_heartbeat else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None
        }


class DeviceAccessCode(db.Model):
    """设备门禁码模型"""
    __tablename__ = 'device_access_codes'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('venue_devices.id'), nullable=False, index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    order_id = db.Column(db.Integer, db.ForeignKey('orders.id'), index=True, comment='关联订单ID')
    activity_id = db.Column(db.Integer, db.ForeignKey('activities.id'), index=True, comment='关联活动ID')
    access_code = db.Column(db.String(100), unique=True, nullable=False, comment='门禁码')
    qr_code_data = db.Column(db.Text, comment='二维码数据')
    code_type = db.Column(db.String(20), default='temporary', comment='码类型: temporary(临时), permanent(永久)')
    valid_from = db.Column(db.DateTime, nullable=False, comment='有效开始时间')
    valid_until = db.Column(db.DateTime, nullable=False, comment='有效结束时间')
    max_uses = db.Column(db.Integer, default=1, comment='最大使用次数')
    used_count = db.Column(db.Integer, default=0, comment='已使用次数')
    status = db.Column(db.SmallInteger, default=1, comment='状态: 0无效 1有效 2已过期 3已用完')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    used_at = db.Column(db.DateTime, comment='最后使用时间')
    
    # 关联关系
    user = db.relationship('User', backref='access_codes')
    order = db.relationship('Order', backref='access_codes')
    
    def __repr__(self):
        return f'<DeviceAccessCode {self.id}: {self.access_code}>'
    
    @staticmethod
    def generate_access_code():
        """生成随机门禁码"""
        return str(uuid.uuid4()).replace('-', '')[:16].upper()
    
    def is_valid(self):
        """检查门禁码是否有效"""
        now = datetime.now()
        return (
            self.status == 1 and
            self.valid_from <= now <= self.valid_until and
            self.used_count < self.max_uses
        )
    
    def use_code(self):
        """使用门禁码"""
        if not self.is_valid():
            return False
        
        self.used_count += 1
        self.used_at = datetime.now()
        
        # 检查是否已用完
        if self.used_count >= self.max_uses:
            self.status = 3  # 已用完
        
        db.session.commit()
        return True
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'id': self.id,
            'device_id': self.device_id,
            'user_id': self.user_id,
            'order_id': self.order_id,
            'activity_id': self.activity_id,
            'access_code': self.access_code,
            'qr_code_data': self.qr_code_data,
            'code_type': self.code_type,
            'valid_from': self.valid_from.strftime('%Y-%m-%d %H:%M:%S') if self.valid_from else None,
            'valid_until': self.valid_until.strftime('%Y-%m-%d %H:%M:%S') if self.valid_until else None,
            'max_uses': self.max_uses,
            'used_count': self.used_count,
            'status': self.status,
            'is_valid': self.is_valid(),
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'used_at': self.used_at.strftime('%Y-%m-%d %H:%M:%S') if self.used_at else None
        }


class DeviceOperationLog(db.Model):
    """设备操作日志模型"""
    __tablename__ = 'device_operation_logs'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('venue_devices.id'), nullable=False, index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
    access_code_id = db.Column(db.Integer, db.ForeignKey('device_access_codes.id'), index=True)
    operation_type = db.Column(db.String(50), nullable=False, comment='操作类型: open_door(开门), close_door(关门), turn_on_light(开灯), turn_off_light(关灯)')
    operation_method = db.Column(db.String(50), comment='操作方式: qrcode(二维码), api(接口), manual(手动)')
    operation_result = db.Column(db.String(20), default='success', comment='操作结果: success(成功), failed(失败)')
    error_message = db.Column(db.Text, comment='错误信息')
    ip_address = db.Column(db.String(45), comment='操作者IP地址')
    user_agent = db.Column(db.String(255), comment='用户代理')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='操作时间')
    
    # 关联关系
    user = db.relationship('User', backref='device_operations')
    access_code = db.relationship('DeviceAccessCode', backref='operation_logs')
    
    def __repr__(self):
        return f'<DeviceOperationLog {self.id}: {self.operation_type}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'id': self.id,
            'device_id': self.device_id,
            'user_id': self.user_id,
            'access_code_id': self.access_code_id,
            'operation_type': self.operation_type,
            'operation_method': self.operation_method,
            'operation_result': self.operation_result,
            'error_message': self.error_message,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'device_name': self.device.device_name if self.device else None,
            'user_name': self.user.nickname if self.user else None
        } 